/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ftpultility;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import javax.swing.JOptionPane;

/**
 *
 * @author Gilmario
 */
public class ZipUtil {

    public String ziparArquivo(String file) {
        byte[] buffer = new byte[18024];
        String zipFileName = file + ".zip";
        try {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
            out.setLevel(Deflater.DEFAULT_COMPRESSION);
            FileInputStream fi = new FileInputStream(file);
            out.putNextEntry(new ZipEntry(new File(file).getName()));
            int len;
            while ((len = fi.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            out.closeEntry();
            fi.close();
            out.close();
            return zipFileName;
        } catch (Exception iae) {
            JOptionPane.showMessageDialog(null, iae);
            return null;
        }
    }

    public void unziparArquivo(String file) {
        try {
            String destinationDirectory = new File(file).getAbsolutePath();
            File sourceZipFile = new File(file);
            File unzipDestinationDirectory = new File(new File(file).getAbsolutePath().replaceAll(new File(file).getName(), ""));
            ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
            Enumeration zipFileEntries = zipFile.entries();
            while (zipFileEntries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
                String currentEntry = entry.getName();
                File destFile = new File(unzipDestinationDirectory, currentEntry);
                File destinationParent = destFile.getParentFile();
                destinationParent.mkdirs();
                if (!entry.isDirectory()) {
                    BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
                    int currentByte;
                    byte data[] = new byte[18050];
                    FileOutputStream fos = new FileOutputStream(destFile);
                    BufferedOutputStream dest = new BufferedOutputStream(fos, 18050);
                    while ((currentByte = is.read(data, 0, 18050)) != -1) {
                        dest.write(data, 0, currentByte);
                    }
                    dest.flush();
                    dest.close();
                    is.close();
                }
            }
            zipFile.close();
        } catch (Exception ioe) {
            JOptionPane.showMessageDialog(null, ioe);
        }
    }
}
